package com.bbs.controller;

import com.bbs.common.Constants;
import com.bbs.entity.BBSPost;
import com.bbs.entity.BBSUser;
import com.bbs.entity.RecentCommentListEntity;
import com.bbs.service.IBBSPostCollectService;
import com.bbs.service.IBBSPostCommentService;
import com.bbs.service.IBBSPostService;
import com.bbs.service.IBBSUserService;
import com.bbs.util.MD5Util;
import com.bbs.util.Result;
import com.bbs.util.ResultGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import sun.security.util.Password;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @PackageName: com.bbs.controller
 * @ClassName: BBSUserController
 * @Description:
 * @Author: Rambo
 * @Data: 2024/6/2 23:37
 */
@Controller
public class BBSUserController {
    @Autowired
    private IBBSUserService bbsUserService;
    @Autowired
    private IBBSPostService bbsPostService;
    @Autowired
    private IBBSPostCommentService bbsPostCommentService;
    @Autowired
    private IBBSPostCollectService bbsPostCollectService;

    /**
     * 注册页面
     * @return
     */
    @GetMapping({"/register", "/register.html"})
    public String registerPage() {
        return "user/reg";
    }

    /**
     * 用户注册方法
     * @param loginName 用户输入的登录名，用于匹配数据库或用户信息存储中的用户名。
     * @param verifyCode 用户输入的验证码，用于校验用户输入的验证码是否正确。
     * @param nickName 用户输入昵称，用于存储用户昵称。
     * @param password 用户输入的密码，用于存储用户密码。
     * @param httpSession HttpSession对象，用于登录成功后存储用户的会话信息。
     * @return
     */
    @PostMapping("/register")
    @ResponseBody
    public Result register(@RequestParam("loginName") String loginName,
                           @RequestParam("verifyCode") String verifyCode,
                           @RequestParam("nickName") String nickName,
                           @RequestParam("password") String password,
                           HttpSession httpSession) {

        // 调用业务层注册方法并返回
        return ResultGenerator.genResult(bbsUserService.register(loginName, password, verifyCode, nickName, httpSession));
    }

    /**
     * 登录页面
     * @return
     */
    @GetMapping({"/login", "/login.html"})
    public String loginPage() {
        return "user/login";
    }

    /**
     * 用户登录方法
     * @param loginName 用户输入的登录名，用于匹配数据库或用户信息存储中的用户名。
     * @param password 用户输入密码，用MD5算法加密后用于匹配数据库或用户信息存储中的密码。
     * @param httpSession HttpSession对象，用于登录成功后存储用户的会话信息。
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public Result login(@RequestParam("loginName") String loginName,
                        @RequestParam("verifyCode") String verifyCode,
                        @RequestParam("password") String password,
                        HttpSession httpSession) {

        // 调用业务层登录方法
        String loginResult = bbsUserService.login(loginName, password, verifyCode, httpSession);

        return ResultGenerator.genResult(loginResult);
    }

    /*
     * 基本设置：获取当前登录用户的 BBSUser 对象并将其传递给后续的请求处理过程或视图渲染，以便在页面中使用该对象的数据
     * */
    @GetMapping("/userSet")
    public String userSetPage(HttpServletRequest request) {
        //获取当前会话对象，然后使用 getAttribute() 方法获取名为 Constants.USER_SESSION_KEY 的属性值
        BBSUser currentUser = (BBSUser) request.getSession().getAttribute(Constants.USER_SESSION_KEY);
        //将 currentUser 对象传递给后续的请求处理过程或视图渲染，以便在页面中使用该对象的数据
        request.setAttribute("bbsUser", currentUser);
        return "user/set";
    }

    /**
     * 修改个人信息
     * @param nickName
     * @param userGender
     * @param location
     * @param introduce
     * @param httpSession
     * @return
     */
    @PostMapping("/updateUserInfo")
    @ResponseBody
    public Result updateInfo(@RequestParam("nickName") String nickName,
                             @RequestParam("userGender") int userGender,
                             @RequestParam("location") String location,
                             @RequestParam("introduce") String introduce,
                             HttpSession httpSession) {
        if (!StringUtils.hasLength(nickName)) {
            return ResultGenerator.genFailResult("nickName参数错误");
        }
        if (userGender < 1 || userGender > 2) {
            return ResultGenerator.genFailResult("userGender参数错误");
        }
        if (!StringUtils.hasLength(location)) {
            return ResultGenerator.genFailResult("location参数错误");
        }
        if (!StringUtils.hasLength(introduce)) {
            return ResultGenerator.genFailResult("introduce参数错误");
        }
        BBSUser bbsUser = (BBSUser) httpSession.getAttribute(Constants.USER_SESSION_KEY);
        if (bbsUser == null) {
            return ResultGenerator.genFailResult("用户对象为空");
        }
        bbsUser.setNickName(nickName);
        if (userGender == 1) {
            bbsUser.setGender("男");
        }
        if (userGender == 2) {
            bbsUser.setGender("女");
        }
        bbsUser.setLocation(location);
        bbsUser.setIntroduce(introduce);
        if (bbsUserService.updateUserInfo(bbsUser, httpSession)) {
            Result result = ResultGenerator.genSuccessResult();
            return result;
        } else {
            Result result = ResultGenerator.genFailResult("修改失败");
            return result;
        }
    }

    /**
     * 修改头像
     * @param userHeadImg
     * @param httpSession
     * @return
     */
    @PostMapping("/updateHeadImg")
    @ResponseBody
    public Result updateHeadImg(@RequestParam("userHeadImg") String userHeadImg,
                                HttpSession httpSession) {

        if (!StringUtils.hasLength(userHeadImg)) {
            return ResultGenerator.genFailResult("userHeadImg参数错误");
        }
        BBSUser bbsUser = (BBSUser) httpSession.getAttribute(Constants.USER_SESSION_KEY);
        bbsUser.setHeadImgUrl(userHeadImg);
        if (bbsUserService.updateUserHeadImg(bbsUser, httpSession)) {
            Result result = ResultGenerator.genSuccessResult();
            return result;
        } else {
            Result result = ResultGenerator.genFailResult("修改失败");
            return result;
        }
    }

    /**
     * 修改密码
     * @param request
     * @param originalPassword
     * @param newPassword
     * @return
     */
    @PostMapping("/updatePassword")
    @ResponseBody
    public Result passwordUpdate(HttpServletRequest request,
                                 @RequestParam("originalPassword") String originalPassword,
                                 @RequestParam("newPassword") String newPassword) {

        if (!StringUtils.hasLength(originalPassword)) {
            return ResultGenerator.genFailResult("originalPassword参数错误");
        }

        BBSUser bbsUser = (BBSUser) request.getSession().getAttribute(Constants.USER_SESSION_KEY);

        // 校验原密码
        String originalPasswordMD5 = MD5Util.MD5Encode(originalPassword, "UTF-8");
        if (!bbsUser.getPasswordMd5().equals(originalPasswordMD5)) {
            return ResultGenerator.genFailResult("原密码错误");
        }

        // 加密新密码
        String newPasswordMD5 = MD5Util.MD5Encode(newPassword, "UTF-8");
        bbsUser.setPasswordMd5(newPasswordMD5);

        if (bbsUserService.updateUserPassword(bbsUser.getUserId(), newPassword, request.getSession())) {
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult("修改失败");
        }
    }

    /**
     * 用户中心
     * @param request
     * @param userId
     * @return
     */
    @GetMapping("/userCenter/{userId}")
    public String userCenterPage(HttpServletRequest request, @PathVariable("userId") Long userId) {
        // 获取用户基本信息
        BBSUser bbsUser = bbsUserService.getUserById(userId);
        if (bbsUser == null) {
            return "error/error_404";
        }

        // 获取最近发布的贴子
         List<BBSPost> recentPostList = bbsPostService.getRecentPostListByUserId(userId);

        // 获取最近的回复内容
        List<RecentCommentListEntity> recentCommentList = bbsPostCommentService.getRecentCommentListByUserId(userId);

        // 封装数据
        request.setAttribute("bbsUser", bbsUser);
        request.setAttribute("recentPostList", recentPostList);
        request.setAttribute("recentCommentList", recentCommentList);

        return "user/home";
    }

    //我的主页
    @GetMapping("/myCenter")
    public String myCenterPage(HttpServletRequest request) {

        //基本用户信息
        BBSUser currentUser = (BBSUser) request.getSession().getAttribute(Constants.USER_SESSION_KEY);

        //我发的贴
        List<BBSPost> myBBSPostList = bbsPostService.getMyBBSPostList(currentUser.getUserId());
        int myBBSPostCount = 0;
        if (!CollectionUtils.isEmpty(myBBSPostList)) {
            myBBSPostCount = myBBSPostList.size();
        }

        //我收藏的贴
        List<BBSPost> collectRecords = bbsPostCollectService.getCollectRecordsByUserId(currentUser.getUserId());
        int myCollectBBSPostCount = 0;
        if (!CollectionUtils.isEmpty(collectRecords)) {
            myCollectBBSPostCount = collectRecords.size();
        }

        request.setAttribute("myBBSPostList", myBBSPostList);
        request.setAttribute("myBBSPostCount", myBBSPostCount);
        request.setAttribute("collectRecords", collectRecords);
        request.setAttribute("myCollectBBSPostCount", myCollectBBSPostCount);
        request.setAttribute("bbsUser", currentUser);
        return "user/index";
    }

    //退出登录
    @GetMapping("/logout")
    public String logout(HttpSession httpSession) {
        httpSession.removeAttribute(Constants.USER_SESSION_KEY);
        return "user/login";
    }
}
